package com.tronsis.distribution.fragment;

import android.graphics.Rect;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.flyco.tablayout.SlidingTabLayout;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.google.gson.Gson;
import com.google.gson.internal.LinkedTreeMap;
import com.google.gson.reflect.TypeToken;
import com.tronsis.distribution.Constants;
import com.tronsis.distribution.R;
import com.tronsis.distribution.adapter.TypeAdapter;
import com.tronsis.distribution.biz.factory.ResourceBizFactory;
import com.tronsis.distribution.eventbus.EventMessage;
import com.tronsis.distribution.eventbus.EventTag;
import com.tronsis.distribution.fragment.material.CategoryFragment;
import com.tronsis.library.adapter.SimpleViewPagerAdapter;
import com.tronsis.library.fragment.BaseFragment;
import com.tronsis.library.http.UICallBack;
import com.tronsis.library.util.KeyboardUtils;
import com.tronsis.library.util.LogUtil;
import com.tronsis.library.util.SharedPreferencesUtil;
import com.tronsis.library.util.StringUtil;
import com.zhy.view.flowlayout.FlowLayout;
import com.zhy.view.flowlayout.TagAdapter;
import com.zhy.view.flowlayout.TagFlowLayout;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;


public class MaterialFragment extends BaseFragment {
    @BindView(R.id.tab_layout)
    SlidingTabLayout mTabLayout;
    @BindView(R.id.viewpager)
    ViewPager mViewPager;
    @BindView(R.id.et_search)
    EditText mEtSearch;
    @BindView(R.id.ib_clear)
    ImageButton mIbClear;
    @BindView(R.id.tv_cancel)
    TextView mTvCancel;
    @BindView(R.id.iv_type)
    ImageView mIvType;
    @BindView(R.id.ll_tab)
    LinearLayout mLlTab;

    private List<Fragment> mPageList = new ArrayList<Fragment>();
    private String mTypeIdsCache;

    private PopupWindow mPopWindow;
    private TagAdapter<String> mTagAdapter;
    private TypeAdapter mTypeAdapter;
    private List<String> mTypeLis = new ArrayList<>();

    @Override
    protected View onCreateView() {
        View view = getActivity().getLayoutInflater().inflate(R.layout.fragment_material, null);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    protected void initData() {

        mTypeIdsCache = SharedPreferencesUtil.getString(mContext, Constants.SP_RES_TYPE_ID_CACHE);
        if (mTypeIdsCache != null) {
            LinkedTreeMap<String, String> linkedTreeMap = (LinkedTreeMap<String, String>) new Gson().fromJson(mTypeIdsCache, new TypeToken<LinkedTreeMap<String, String>>() {
            }.getRawType());
            setViewPager(linkedTreeMap);
        }

        mEtSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    searchClick();
                    return true;
                }
                return false;
            }
        });
        mEtSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.length() > 0) {
                    mIbClear.setVisibility(View.VISIBLE);
                } else {
                    mIbClear.setVisibility(View.GONE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int i, float v, int i1) {

            }

            @Override
            public void onPageSelected(int i) {
                if (mTypeAdapter != null) {
                    mTypeAdapter.setCheckItem(i);
                }
            }

            @Override
            public void onPageScrollStateChanged(int i) {

            }
        });


        httpGetTypes();
    }


    private void showPopupWindow() {
        //设置contentView
        View contentView = LayoutInflater.from(getActivity()).inflate(R.layout.popup_menu, null);
        if (mPopWindow == null) {
            mPopWindow = new PopupWindow(contentView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
            mPopWindow.setContentView(contentView);
            final TagFlowLayout mFlowLayout = contentView.findViewById(R.id.id_flowlayout);
            final LayoutInflater mInflater = LayoutInflater.from(getActivity());
            mTagAdapter = new TagAdapter<String>(mTypeLis) {
                @Override
                public View getView(FlowLayout parent, int position, String s) {
                    TextView tv = (TextView) mInflater.inflate(R.layout.item_text_view,
                            mFlowLayout, false);
                    tv.setText(s);
                    return tv;
                }
            };
            mFlowLayout.setAdapter(mTagAdapter);

            mFlowLayout.setOnTagClickListener(new TagFlowLayout.OnTagClickListener() {
                @Override
                public boolean onTagClick(View view, int position, FlowLayout parent) {
                    mTabLayout.setCurrentTab(position);
                    return false;
                }
            });


            View view = contentView.findViewById(R.id.view_half_transparent);

            view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mPopWindow.dismiss();
                }
            });
        }

        if (mTabLayout != null) {
            mTagAdapter.setSelectedList(mTabLayout.getCurrentTab());
        }

        showAsDropDown(mPopWindow,mLlTab,0,0);
    }


    public static void showAsDropDown(final PopupWindow pw, final View anchor, final int xoff, final int yoff) {
        if (Build.VERSION.SDK_INT >= 24) {
            Rect visibleFrame = new Rect();
            anchor.getGlobalVisibleRect(visibleFrame);
            int height = anchor.getResources().getDisplayMetrics().heightPixels - visibleFrame.bottom;
            pw.setHeight(height);
            pw.showAsDropDown(anchor, xoff, yoff);
        } else {
            pw.showAsDropDown(anchor, xoff, yoff);
        }
    }


    @OnClick(R.id.iv_search)
    void searchClick() {
        String search = mEtSearch.getText().toString();
        EventBus.getDefault().post(new EventMessage(EventTag.MATERIAL_SEARCH, search));
        KeyboardUtils.hideSoftInput(mEtSearch);
    }

    @OnClick(R.id.ib_clear)
    void etClearClick() {
        mEtSearch.setText("");
    }


    @OnClick(R.id.tv_cancel)
    void searchCancelClick() {
        mEtSearch.setText("");
        KeyboardUtils.hideSoftInput(mEtSearch);
        EventBus.getDefault().post(new EventMessage(EventTag.MATERIAL_SEARCH, null));

    }

    @OnClick(R.id.iv_type)
    void typeClick() {
        showPopupWindow();
    }

    private void httpGetTypes() {
        try {
            ResourceBizFactory.createBiz().getResourceType(getActivity(), false, new UICallBack() {
                @Override
                public void onStart() {

                }

                @Override
                public void onRefresh(Object data) {
                    LinkedTreeMap<String, String> linkedTreeMap = (LinkedTreeMap<String, String>) data;
                    if (linkedTreeMap == null) {
                        return;
                    }
                    String typeIds = new Gson().toJson(linkedTreeMap);
                    LogUtil.d("type-json", typeIds);
                    if (!StringUtil.isEquals(typeIds, mTypeIdsCache)) {
                        SharedPreferencesUtil.putString(mContext, Constants.SP_RES_TYPE_ID_CACHE, typeIds);
                        setViewPager(linkedTreeMap);
                    }
                }

                @Override
                public void onFailure(int status) {

                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void setViewPager(LinkedTreeMap<String, String> linkedTreeMap) {
        if (linkedTreeMap == null) {
            return;
        }
        mPageList.clear();
        mTypeLis.clear();

        CategoryFragment fm = new CategoryFragment();
        mPageList.add(fm);
        Bundle bd = new Bundle();
        bd.putString("typeId", null);
        fm.setArguments(bd);
        mTypeLis.add("全部");

        Iterator it = linkedTreeMap.keySet().iterator();
        while (it.hasNext()) {
            String key = (String) it.next();
            String value = linkedTreeMap.get(key);
            CategoryFragment fragment = new CategoryFragment();
            mPageList.add(fragment);
            Bundle bundle = new Bundle();
            bundle.putString("typeId", key);
            fragment.setArguments(bundle);
            mTypeLis.add(value);
        }

        String[] mTitles = mTypeLis.toArray(new String[0]);
        SimpleViewPagerAdapter adapter = new SimpleViewPagerAdapter(getActivity().getSupportFragmentManager(), mPageList);
        mViewPager.setAdapter(adapter);

        for (int i = 0; i < mTitles.length; i++) {
            if (mTitles[i] != null && mTitles[i].length() > 4) {
                mTitles[i] = mTitles[i].substring(0, 4);
            }
        }
        mTabLayout.setViewPager(mViewPager, mTitles);

        mTabLayout.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                if (mTypeAdapter != null) {
                    mTypeAdapter.setCheckItem(position);
                }
            }

            @Override
            public void onTabReselect(int position) {

            }
        });
    }


}
